package com.bjfl.saleManager.util;

import android.text.TextUtils;

import com.event.MqttEvent;
import com.log.LatteLogger;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by 86463
 * Created time: 2018/2/5/16:36
 */

public class MqttUtil {

    private static final String HOST = "tcp://39.107.53.38:1883";
    private static final String USER = "bjfl";
    private static final String PASSWORD = "BjFulei!@#$";
    private static final String CLIENTID = "test";
    private static MqttClient client;
    private static MqttConnectOptions options;


    public static MqttUtil getMqttUtilInstance() {
        return MqttUtilHolder.INSTANCE;
    }

    private static final class MqttUtilHolder {
        private static final MqttUtil INSTANCE = new MqttUtil();
    }

    private MqttUtil() {
        init();
    }

    private static void init() {
        try {
            client = new MqttClient(HOST, CLIENTID, new MemoryPersistence());
            options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setUserName(USER);
            options.setPassword(PASSWORD.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);

            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {

                    LatteLogger.i("mqtt", "connection lost");
//                    startReconnect();
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    LatteLogger.i("mqtt", "message is arriving");
                    // TODO: 2018/2/5  eventBus发送消息
                    EventBus.getDefault().post(new MqttEvent(message));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {

                    LatteLogger.i("mqtt", "deliverycomplete" + token.isComplete());
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private static ScheduledExecutorService scheduledExecutorService;

    public void startReconnect(final String topic) {

        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    connect(topic);
                }
            }
        }, 0, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    private static final String TOPIC = "test/topic";

    private static void connect(String topic) {
        try {
            client.connect(options);
            if (TextUtils.isEmpty(topic)) {
                client.subscribe(TOPIC,2);
                LatteLogger.i("mqtt","连接成功");
            } else {
                client.subscribe(topic,2);
                LatteLogger.i("mqtt","连接成功");
            }

        } catch (MqttException e) {
            e.printStackTrace();

        }
    }

    public static void releaseMqtt() {
        try {
            if (client != null) {
                client.disconnect();
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
